package com.netty.coder;


import utl.mofen.objects.JSonStream;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

public class JSonStreamDecoder extends ByteToMessageDecoder<JSonStream> {
	

	
	/*****
	 * 4 jsonLength
	 * 8 streamLength
	 * jsonString
	 * stream 
	 */
	@Override	
	public JSonStream decode(ChannelHandlerContext ctx, ByteBuf in)
			throws Exception {

		int l = in.readableBytes();
		
		if (l < 12) {
            return null;
        }
		


        in.markReaderIndex();        
        
        int jsonLength = in.readInt();
		int streamLength = in.readInt();
		if (in.readableBytes() < (jsonLength + streamLength))
		{
			in.resetReaderIndex();
			return null;
		}
		
		JSonStream ret = new JSonStream();
		byte[] bytes = new byte[jsonLength];
		
		in.readBytes(bytes);
		
		String jsonStr = new String(bytes, "UTF-8");
		ret.setJsonString(jsonStr);
	
		bytes = new byte[streamLength];
		in.readBytes(bytes);
		ret.setStream(bytes);
        return ret;
		
	}

}
